import {
	token,
	userInfo,
} from "@/utils/token.js"
import {
	appId
} from "@/config.js"
import {
	genTestUserSig
} from './GenerateTestUserSig.js';

import TIM from '@/common/js/tim-wx.js';

export default {
	data() {
		return {
			durationList: [{
					name: '一周内',
					value: 0,
				},
				{
					name: '一月内',
					value: 1,
				},
				{
					name: '半年内',
					value: 2,
				},
				{
					name: '半年以上',
					value: 3,
				}
			],
			izLookHospList: [{
					name: '未就诊',
					value: 0,
				},
				{
					name: '就诊过',
					value: 1,
				},

			],
			orderTypeList: [{
					name: '专家问诊',
					value: 0,
				},
				{
					name: '极速问诊',
					value: 1,
				},
				{
					name: '开药问诊',
					value: 2,
				},

			],
			inquiryTypeList: [{
					name: '图文咨询',
					value: 0,
				},
				{
					name: '视频咨询',
					value: 1,
				}
			],

			birthStatusList: [{
					name: '无',
					value: 0,

				},
				{
					name: '准备要孩子',
					value: 1,

				},
				{
					name: '怀孕中',
					value: 2,

				},
				{
					name: '正在哺乳',
					value: 3,

				}
			],

			functionList: [{
					name: '正常',
					value: 0,
				},
				{
					name: '异常',
					value: 1,
				},
				{
					name: '不清楚',
					value: 2,
				}
			],
			allergyList: [{
					name: '无',
					value: 0,
				},
				{
					name: '有',
					value: 1,
				},
				{
					name: '不清楚',
					value: 2,
				}
			],
			rangeSex: [{
				value: "1",
				text: '男'
			}, {
				value: "2",
				text: '女'
			}],
			jobGradeConfig: ['住院医师', '主治医师', '副主任医师', '主任医师'],
			checkStatusConfig: ['认证中', '已认证', '已驳回'],
			orderStatusList: [
				"支付中",
				"支付成功",
				"支付失败",
				"待支付",
				"退款中",
				"已退款",
				"已取消",
				"待发货",
				"待收货",
				"已评价",
				"已完成"
			],

			orderStatusList2: [
				"待支付",
				"待发货",
				"已发货",
				"已签收",
				"已评价",
				"售后中",
				"订单关闭",
				"已取消"
			],

			serviceStatusList: [
				"待接诊",
				"问诊中",
				"已开处方",
				"已完成",
				"已退诊"
			],


			recipeStatusList: [
				"待审核",
				"已审核",
				"已购买",
				"已失效",
				"审核未通过"
			],
			inquiry: true,
			appInitStatus: false
		}
	},
	onLoad(options) {
		// this.queryCheckConfig()
		//开启小程序分享
		uni.showShareMenu({
			title: '',
			path: options.path,
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});

	},





	methods: {
		/**
		 * 查询审核配置
		 */
		queryCheckConfig(options) {
			this.$api.queryCheckConfig({}).then(res => {
				if (res.code == 200) {
					if (res.result == "1") {
						// uni.setStorageSync('inquiry', false);
						let pages = getCurrentPages()[0].$page;
						if (pages.fullPath != "/pages/index/index") {
							uni.reLaunch({
								url: "/pages/index/index"
							})
						}
					}
					// this.inquiry = uni.getStorageSync('inquiry') ? uni.getStorageSync('inquiry') : false;
					this.inquiry = true;
					this.appInitStatus = true
					uni.$emit("appInit")
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				}
			});
		},

		//路由跳转
		gotoRouter(url, data = null) {
			uni.navigateTo({
				url: url,
				success: res => {
					if (data) {
						res.eventChannel.emit('data', data);
					}
				},
				fail: err => {
					uni.switchTab({
						url: url
					});
				}
			});
			// if (!token.get()) {
			// 	this.wxLogin()
			// } else {

			// 	uni.navigateTo({
			// 		url: url,
			// 		success: res => {
			// 			if (data) {
			// 				res.eventChannel.emit('data', data);
			// 			}
			// 		},
			// 		fail: err => {
			// 			uni.switchTab({
			// 				url: url
			// 			});
			// 		}
			// 	});
			// }
		},


		//切换客户端
		switchClient(data, type) {
			if (data) {
				var doctorId = data.id;
				var doctorName = data.doctorName;
				var picture = data.pictureUrl;
				var hospitalName = data.hospitalName;
				var departmentName = data.departmentName;
			}

			var wxUser = userInfo.get();
			if (type == 0) {
				getApp().globalData.role = 0;
				//切换端重登im
				this.imLogin(wxUser.id, wxUser.nickname, wxUser.avatar, wxUser.openId, wxUser.sex, '', '');
				uni.reLaunch({
					url: '/pages/index/index'
				});
			} else if (type == 1) {
				getApp().globalData.role = 1;
				//切换端重登im
				this.imLogin(doctorId, doctorName, picture, wxUser.openId, wxUser.sex, hospitalName, departmentName);
				uni.reLaunch({
					url: '/pages/doctor/doctor'
				});
			} else if (type == 2) {
				getApp().globalData.role = 2;
				//切换端重登im
				this.imLogin(doctorId, doctorName, picture, wxUser.openId, wxUser.sex, hospitalName, departmentName);
				uni.reLaunch({
					url: '/pages-doctor/pharmacist/pharmacist'
				});
			}
		},


		imLogin(userID, name, avatar, openId, sex = '', hospitalName = "", departmentName = "") {

			const userSig = genTestUserSig(userID).userSig;
			const SDKAppID = getApp().globalData.SDKAppID;
			console.log(`TUI-login | login  | userSig:${userSig} userID:${userID}`);

			getApp().globalData.userInfo = {
				userSig,
				userID
			};
			uni.setStorageSync(`TIM_${SDKAppID}_isTUIKit`, true);

			uni.$TUIKit.logout()
				.finally(err => {
					uni.$TUIKit
						.login({
							userID: userID,
							userSig: userSig
						})
						.then(imResponse => {
							if (imResponse.data.repeatLogin === true) {
								// 标识帐号已登录，本次登录操作为重复登录。v2.5.1 起支持
								console.log(imResponse.data.errorInfo);
							}

							uni.$once('isSDKReady', res => {
								if (res.isSDKReady) {
									this.updateImUserInfo(name, avatar, openId, sex, hospitalName,
										departmentName)
								}

							})


						})
						.catch(imError => {
							console.warn('login error:', imError); // 登录失败的相关信息
						});
				})
		},



		updateImUserInfo(name, avatar, openId, sex, hospitalName, departmentName) {
			console.log("修改个人资料", name, avatar, openId, sex, hospitalName, departmentName)
			// 修改个人标配资料
			uni.$TUIKit.updateMyProfile({
				nick: name,
				avatar: avatar,
				selfSignature: openId,
				profileCustomField: [{
						key: 'Tag_Profile_Custom_sex',
						value: sex + ""
					},
					{
						key: 'Tag_Profile_Custom_hospName',
						value: hospitalName
					},
					{
						key: 'Tag_Profile_Custom_ksName',
						value: departmentName
					},
				]
			}).then(imResponse => {
				console.log("updateMyProfile success:", imResponse.data); // 更新资料成功
			}).catch(imError => {
				console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
			});
		},


		//微信登录
		wxLogin(type = 1) {

			uni.showLoading({
				title: '登录中...',
				mask: true
			});

			let p1 = this.wxSilentLogin()
			let p2 = this.wxGetUserProfile()

			Promise.all([p1, p2]).then((res) => {
				let code = res[0]
				let iv = res[1].iv
				let encryptedData = res[1].encryptedData
				let signature = res[1].signature
				let rawData = res[1].rawData
				let wxUserInfo = res[1].userInfo
				// 请求服务器
				this.$api.wxLogin({
					data: {
						appId,
						code,
						encryptedData,
						iv,
						rawData,
						signature,
						userInfo: wxUserInfo
					},
				}).then(res => {
					uni.hideLoading();
					if (res.code == 200) {
						uni.showToast({
							title: "登录成功",
							icon: 'none'
						})

						let wxUser = res.result.user

						token.set(res.result.token, Date.parse(new Date()) + (86400000 * 29));
						userInfo.set(wxUser, Date.parse(new Date()) + (86400000 * 29))


						if (type != 2) {
							this.imLogin(wxUser.id, wxUser.nickname, wxUser.avatar, wxUser.openId,
								wxUser.sex)
							uni.$emit("wxLogin")


							let hospitalId = uni.getStorageSync("hospitalId")
							let referrerDoctorId = uni.getStorageSync("referrerDoctorId")
							let scene = uni.getStorageSync("scene")
							if (hospitalId) {
								this.userBindHospital(hospitalId, referrerDoctorId, scene)
							}


							wx.setEnable1v1Chat({
								enable: true,
								success: res => {
									console.log('加载1v1视频通话成功', res);
								},
								fail: err => {
									console.log('加载1v1视频通话失败', err);
								}
							});

						}

					} else {
						uni.showToast({
							title: res.message,
							icon: "none"
						})
					}

				}).catch(err => {
					uni.hideLoading();
					// uni.showToast({
					// 	title: "登录失败",
					// 	icon: 'none'
					// })
				})
			}).catch((err) => {
				uni.hideLoading();
				uni.showToast({
					title: "登录请求失败",
					icon: 'none'
				})
			})
		},


		//用户绑定医院
		userBindHospital(hospitalId, referrerDoctorId, scene) {

			let params = {
				hospitalId: hospitalId
			}
			if (referrerDoctorId) {
				params.referrerDoctorId = referrerDoctorId
			}
			if (scene) {
				params.userScene = scene
			}

			this.$api
				.userBindHospital({
					params: params
				})
				.then(res => {
					if (res.code == 200) {
						userInfo.set(res.result, Date.parse(new Date()) + (86400000 * 29))
						uni.$emit("wxLogin")
					}
				});
		},


		wxGetUserProfile() {
			return new Promise((resolve, reject) => {
				wx.getUserProfile({
					lang: 'zh_CN',
					desc: '用户登录',
					success: (res) => {
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		},

		wxSilentLogin() {
			return new Promise((resolve, reject) => {
				wx.login({
					success(res) {
						resolve(res.code)
					},
					fail(err) {
						reject(err)
					}
				})
			})
		},



		//复制内容到剪切版
		setClipboardData(data) {
			uni.setClipboardData({
				data: data,
				success: res => {
					uni.showToast({
						title: '复制成功',
						icon: "none"
					});
				}
			});
		},


		//预览图片
		previewImage(imgs, index) {
			uni.previewImage({
				urls: imgs,
				loop: true,
				current: index
			});
		},



	}
}
